package com.exigenservices.demenkov.model.dao.Impl;

import com.exigenservices.demenkov.model.dao.GenericDAO;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

/**
 * Implementation of Generic DAO
 *
 * @Author DemYura
 * @Date 24.11.11
 */
@Repository
public class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {
    @PersistenceContext
    protected EntityManager entityManager;

    private Class<T> getType() {
        return (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public void update(T entity) {
        entityManager.merge(entity);
    }


    public void create(T entity) {
        entityManager.persist(entity);
    }

    public void delete(T entity) {
        entityManager.remove(entity);
    }

    public T get(ID id) {
        return entityManager.find(getType(), id);
    }
}
